<?php

namespace App\Admin\Controllers\Machine;

use App\Admin\Renderable\GoodsRenderable;
use App\Logic\LogLogic;
use App\Models\SwtGood;
use App\Models\SwtMachineGood;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;

class SwtMachineGoodController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $machine_id = request()->get('machine_id');

        if(!$machine_id) {
            return '请选择设备';
        }

        return Grid::make( SwtMachineGood::with('goods'), function (Grid $grid) use($machine_id){
            $grid->tools(function (Grid\Tools $tools) use($machine_id){
                $url = admin_url('/machine/swt_machine');
                $button = <<<HTML
<div class="btn-group pull-left" style="margin-right: 5px">
    <a href="{$url}" class="btn btn-sm btn-primary "><i class="feather icon-skip-back"></i><span class="d-none d-sm-inline">&nbsp;返回</span></a>
</div>
HTML;
                $tools->append($button);
            });

            $grid->column('id')->sortable();
            $grid->column('goods.goods_picture','商品图')->image('',60,60);
            $grid->column('goods.goods_name','商品名');
            $grid->column('weight') -> display( function ($value) {
                return $value > 0 ? "<span class='text-success'>{$value}</span>" : "<span class='text-danger'>{$value}</span>";
            });
            $grid->column('max_weight','最大库存');
            $grid->column('sell_price') -> display( function ($value) {
                return '¥'.bcdiv($value, 100, 2);
            });
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->disableFilterButton();
            $grid->disableRefreshButton();

            $grid->disableCreateButton(false);
            $grid->disableDeleteButton(false);

            $grid->enableDialogCreate();

            $grid->model()->setConstraints([
                'machine_id' => $machine_id,
            ]);

            $grid->actions(function (Grid\Displayers\Actions $actions) {
               $actions -> quickEdit();
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('machine_id');
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $machine_id = request()->get('machine_id');

        return Form::make(new SwtMachineGood(), function (Form $form) use ($machine_id) {
            $form->hidden('machine_id')->value($machine_id);

            $form -> selectTable('goods_id','商品')
                -> title('商品表')
                -> from(GoodsRenderable::make())
                -> rules('required', ['required' => '商品不能为空'])
                -> model(SwtGood::class, 'id', 'goods_name')
                -> required();

            $form->text('weight')->type('number')->required() -> rules('lte:max_weight');

            $form->text('max_weight','最大库存')->type('number')->required()->default(10);

            $form->currency('sell_price')->customFormat(function ($value) {
                return $value / 100;
            })->symbol('¥');

            $form->saving(function (Form $form) {
                $form -> sell_price *= 100;

                $goods_info = SwtGood::where('id', $form->goods_id)->first();

                if($form -> sell_price == 0) {
                    $form -> sell_price = $goods_info -> sell_price;
                }

                $info = false;

                $num = 0;

                if($form->isCreating()) {
                    $info = SwtMachineGood::where('machine_id', $form->machine_id) -> where('goods_id', $form->goods_id) -> first();
                    $num = $form -> weight;
                }

                if($form->isEditing()) {
                    $info = SwtMachineGood::where('id','<>',$form->getKey())->where('machine_id', $form->machine_id) -> where('goods_id', $form->goods_id) -> first();
                    $num = $form -> weight - $form -> model() -> weight;
                }

                if($info) {
                    return $form->response()->error('商品已存在');
                }
                $user = Admin::user();
                $goods = [
                    [
                        'goods_name' => $goods_info -> goods_name,
                        'num'        => $num
                    ]
                ];
                LogLogic::setMachineGoodsLogs($form->machine_id, $user->id, $goods, '后台变更');
            });

            $form -> deleting(function (Form $form) {
                $arr = $form -> model() -> toArray()[0];

                $goods_info = SwtGood::where('id', $arr['goods_id'])->first();

                $num = $arr['weight'] * -1;

                $user = Admin::user();

                $goods = [
                    [
                        'goods_name' => $goods_info -> goods_name,
                        'num'        => $num
                    ]
                ];

                LogLogic::setMachineGoodsLogs($arr['machine_id'], $user->id, $goods, '后台变更');
            });
        });
    }
}
